package com.gitee.dufafei.plugin.vfs;

import com.gitee.dufafei.plugin.core.PluginException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelectInfo;
import org.apache.commons.vfs2.FileSelector;

import java.io.IOException;

public class Folder implements FolderInterface {

    private FileObject folderObject;

    public Folder(String folder) { this.folderObject = FileVFS.getFileObject(folder); }

    @Override
    public String getPath() { return FileVFS.getFileName(folderObject); }

    @Override
    public boolean isExists() {
        try {
            return folderObject.exists();
        } catch (IOException e) {
            throw new PluginException(e);
        }
    }

    @Override
    public FileObject[] findJarFiles(final boolean includeLibDir) {
        try {
            return folderObject.findFiles(new FileSelector() {
                /**
                 * Determine whether the directory should be traversed.
                 */
                @Override
                public boolean traverseDescendents(FileSelectInfo fileSelectInfo) throws Exception {
                    FileObject fileObject = fileSelectInfo.getFile();
                    FileObject ignore = fileObject.getChild(".ignore");
                    String folder = fileObject.getName().getBaseName();
                    return includeLibDir || (!"lib".equals(folder) && ignore == null);
                }

                /**
                 * Filter JAR files
                 */
                @Override
                public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception {
                    FileObject file = fileSelectInfo.getFile();
                    return file.isFile() && file.toString().endsWith(".jar");
                }
            });
        } catch (Exception e) {
            throw new PluginException("Unable to list jar files in folder '" + toString() + "'", e);
        }
    }

    @Override
    public String toString() { return getPath(); }
}
